package na.learn.java.corepatterns.pooling;

import java.util.Hashtable;
import java.util.WeakHashMap;

//Singleton
public class ConnectionManager {

	private CommonParams commonParams = null;

	private static ConnectionManager connManager = null;

	//	 A Hashtable containing (key=hostURL, value = configurationMap)
	private WeakHashMap configurationMap;

	// A Hashtable containing (key=configurationMap, value = connection)
	private ConnectionPool connectionPool;

	private ConnectionManager() {
		super();
		connectionPool = new ConnectionPool();
	}

	// Singleton
	public static final ConnectionManager getInstance() {
		if (connManager == null) {
			synchronized (connManager) {
				if (connManager == null)
					connManager = new ConnectionManager();

			}
		}
		connManager.commonParams = new CommonParams();		
		return connManager;

	}

	public void setParams(CommonParams commonParams) {
		this.commonParams = commonParams;
	}

	@Override
	protected Object clone() throws CloneNotSupportedException {
		throw new CloneNotSupportedException("Single can not be cloned. ");
	}
	
	
	public Connection getConnection(HostSpecificParams hostparams) {
		Connection conn = connectionPool.getFreeConnection(hostparams);
		if(configurationMap== null)
			configurationMap = new WeakHashMap();
		/*configurationMap.put();*/
		return null;

	}

	class ConnectionPool {

		private int numHosts;

		private int totalLiveConnections;

		private Hashtable pool = new Hashtable();

		/**
		 * 1. If there is any free connection in Pool for this host, return it.
		 * else if ( num_Of_In-use_Connections_for_this_host < minConnPerHost), create and return a new connection.
		 * else (if num_Of_In-use_Connections_for_this_host >= minConnPerHost and < maxConnectionsPerHost)
		 * 	2. create a new Connection and return it.
		 * else if( Total_IN-use_connections is less than maxTotalConnections),
		 * 	3. create a new Connection and return it.
		 *  
		 * @param hostParams
		 * @return
		 */
		public Connection getFreeConnection(HostSpecificParams hostParams) {

			return null;

		}

	}

}
